/**
*      author: Y_Yao
*      created: 2024-12-11 22:53:36
**/

#include<bits/stdc++.h>

#define int LL
using namespace std;
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
const signed N = 300 + 7;
int a[N][N];
int m;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
bool vis[N][N];
int step;
int flag = 1;
int ans = 0;
struct node
{
    int x,y,step;
};

void bfs()
{
    queue<node> q;
    q.push({0,0,1});
    vis[0][0] = true;

    while(!q.empty())
    {
        auto t = q.front();
        q.pop();
        int x = t.x,y = t.y;
        if(a[x][y] == -1)
        {
            flag = 0;
            step = t.step;
            return;
        }

        for(int j = 0;j < 4;j++)
        {
            int ta = x + dx[j],tb = y + dy[j];
            if(vis[ta][tb]) continue;
            if(ta < 0 || ta > 305 || tb < 0 || tb > 305 || (t.step >= a[ta][tb] && a[ta][tb] != -1)) continue;
            vis[ta][tb] = true;
            q.push({ta,tb,t.step + 1});
        }
    }
}

void solve()
{
    cin >> m;
    memset(a,-1,sizeof a);
    for(int i = 1;i <= m;i++)
    {
        int x,y,t;
        cin >> x >> y >> t;
        if(t < a[x][y] || a[x][y] == -1) a[x][y] = t;
        for(int j = 0;j < 4;j++)
        {
            int ta = x + dx[j],tb = y + dy[j];
            if(ta < 0 || ta > 300 || tb < 0 || tb > 300 || (a[ta][tb] < t && a[ta][tb] != -1)) continue;
            a[ta][tb] = t;
        }
    }
    // for(int i = 0;i <= 5;i++)
    // {
    //     for(int j = 0;j <= 5;j++)
    //     {
    //         cout << a[i][j] << " ";
    //     }
    //     cout << endl;
    // }

    bfs();
    if(flag == 1) cout << -1 << endl;
    else cout << step - 1 << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    //cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}